package com.xiaoyu.lanling.feature.coin.activity

import `in`.srain.cube.app.lifecycle.AppActivityLifecycleCallbacks
import `in`.srain.cube.util.StringUtil
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentActivity
import com.xiaoyu.base.app.App
import com.xiaoyu.base.app.AppContext
import com.xiaoyu.base.event.AppEventBus
import com.xiaoyu.base.event.SimpleEventHandler
import com.xiaoyu.base.utils.extensions.getViewTag
import com.xiaoyu.base.utils.extensions.setOnClickDebounceListener
import com.xiaoyu.base.utils.extensions.setViewTag
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.activity.base.BaseDialogFragment
import com.xiaoyu.lanling.common.Constant
import com.xiaoyu.lanling.event.coin.CoinRechargeProductListEvent
import com.xiaoyu.lanling.event.pay.PreparePayEvent
import com.xiaoyu.lanling.feature.coin.data.CoinData
import com.xiaoyu.lanling.feature.coin.data.CoinEventLogManger
import com.xiaoyu.lanling.feature.coin.model.CoinRechargeProductItem
import com.xiaoyu.lanling.feature.pay.data.PayData
import com.xiaoyu.lanling.router.Router
import com.xiaoyu.lanling.util.TextViewUtil
import com.xiaoyu.pay.ALI_PAY
import com.xiaoyu.pay.PayUtil
import com.xiaoyu.pay.WE_CHAT_PAY
import com.xiaoyu.pay.event.PayEvent
import kotlinx.android.synthetic.main.dialog_coin_recharge.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class CoinRechargeDialogFragment : BaseDialogFragment() {

    companion object {
        val TAG: String = CoinRechargeDialogFragment::class.java.simpleName

        fun show(from: String) {
            if (!AppActivityLifecycleCallbacks.getInstance().isAppInForeground) {
                return
            }
            (App.getInstance().topActivity as? FragmentActivity)?.let {
                if (it.isFinishing || it.isDestroyed) {
                    return@let
                }

                val arguments = Bundle()
                arguments.putString(Constant.PARAM_FROM, from)

                val dialogFragment = (it.supportFragmentManager.findFragmentByTag(TAG) as? CoinRechargeDialogFragment)
                        ?: CoinRechargeDialogFragment()
                dialogFragment.arguments = arguments
                dialogFragment.setOnDismissListener(it as? OnDismissListener)
                dialogFragment.show(it.supportFragmentManager, TAG)
            }
        }
    }

    private val requestTag = Any()

    private val payUtil = PayUtil()

    private lateinit var from: String
    private var mProductId: String? = null
    private var mProducts: MutableList<CoinRechargeProductItem>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.DialogFullScreenDimStyle)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.dialog_coin_recharge, container, false)
    }

    override fun onViewCreatedSafelyAfterAppFinishInit(view: View, savedInstanceState: Bundle?) {
        initBind()
        initEvent()
        initData()
        CoinEventLogManger.chargeDialogShow()
    }

    private fun initBind() {
        close.setOnClickDebounceListener {
            CoinEventLogManger.chargeDialogCloseClick()
            dismiss()
        }
        coin_thousand_layout.setOnClickDebounceListener {
            val item = it.getViewTag<CoinRechargeProductItem>() ?: return@setOnClickDebounceListener
            performSelected(0, item)
        }
        coin_thirty_layout.setOnClickDebounceListener {
            val item = it.getViewTag<CoinRechargeProductItem>() ?: return@setOnClickDebounceListener
            performSelected(1, item)
        }
        coin_more.setOnClickListener {
            val activity = activity ?: return@setOnClickListener
            CoinEventLogManger.chargeDialogMoreClick()
            Router.instance.gotoCoinProductListAndBalanceActivity(activity)
        }
        ali_pay.setOnClickDebounceListener { selectPayWay(ALI_PAY) }
        wechat_pay.setOnClickDebounceListener { selectPayWay(WE_CHAT_PAY) }
        coin_charge_dialog_button.setOnClickListener {
            mProductId?.let {
                when {
                    wechat_pay.isSelected -> PayData.preparePay(requestTag, it, WE_CHAT_PAY, from)
                    ali_pay.isSelected -> PayData.preparePay(requestTag, it, ALI_PAY, from)
                }
            }
        }
    }

    private fun initEvent() {
        AppEventBus.bindContainerAndHandler(this, object : SimpleEventHandler() {
            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: PreparePayEvent) {
                if (event.isNotFromThisRequestTag(requestTag)) {
                    return
                }

                when (event.payWay) {
                    ALI_PAY -> payUtil.toAliPay(event.params)
                    WE_CHAT_PAY -> payUtil.toWeChatPay(event.params)
                }
            }

            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: PayEvent) {
                dismiss()
            }

            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: CoinRechargeProductListEvent) {
                mProducts = event.products
                event.products.forEachIndexed { index, item ->
                    when (index) {
                        0 -> {
                            coin_thousand_title.text = item.subject
                            coin_thousand_subtitle.text = AppContext.getString(R.string.coin_charge_dialog_price_suffix, item.price)
                            coin_thousand_layout.setViewTag(item)
                            TextViewUtil.displayOrGone(coin_thousand_tip, item.discountDesc)
                        }
                        1 -> {
                            coin_thirty_title.text = item.subject
                            coin_thirty_subtitle.text = AppContext.getString(R.string.coin_charge_dialog_price_suffix, item.price)
                            coin_thirty_layout.setViewTag(item)
                            TextViewUtil.displayOrGone(coin_thirty_tip, item.discountDesc)
                        }
                    }
                }
                performSelected(1)
            }
        })
    }

    private fun initData() {
        arguments?.let {
            from = it.getString(Constant.PARAM_FROM) ?: StringUtil.blank()
            CoinData.getRechargeProductList(requestTag, from)
            selectPayWay(WE_CHAT_PAY)
        }
    }

    private fun performSelected(index: Int, item: CoinRechargeProductItem? = null) {
        item?.let {
            CoinEventLogManger.chargeDialogProductClick(it.price, it.productId)
        }

        mProducts?.let {
            mProductId = it[index].productId

            when (index) {
                0 -> {
                    coin_thousand_layout.isSelected = true
                    coin_thirty_layout.isSelected = false
                }
                1 -> {
                    coin_thousand_layout.isSelected = false
                    coin_thirty_layout.isSelected = true
                }
            }
        }
    }

    private fun selectPayWay(payWay: String) {
        when (payWay) {
            ALI_PAY -> {
                ali_pay.isSelected = true
                wechat_pay.isSelected = false
            }
            WE_CHAT_PAY -> {
                ali_pay.isSelected = false
                wechat_pay.isSelected = true
            }
        }
    }
}